package com.example.demo.jacob;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Test1 {

    public static void main(String[] args)
    {
        ComThread.startMainSTA();
        String path="E:\\06_xisoft\\02_code\\jacob-demo\\src\\main\\java\\com\\jacob\\samples\\office\\TestDocument.doc";
        ActiveXComponent wordApp = new ActiveXComponent("Word.Application");
        Object xlo = wordApp.getObject();
        Dispatch aDoc = null;
        Dispatch wordDocs = null;
        try {
            ComThread.InitMTA(true);
            wordApp.setProperty("Visible", new Variant(true));
            wordApp.setProperty("AutomationSecurity", new Variant(3));
            log.info("word 资源对象wordApp=[{}]", wordApp);
            try {
                wordApp.setProperty("Visible", new Variant(false));
                wordDocs = wordApp.getProperty("Documents").toDispatch();
            } catch (Exception e) {
                throw new RuntimeException("初始化jacob资源失败！", e);
            }
            log.info("word 初始化资源信息：[{}]", wordApp.getObject());
            // 2. open
            Variant va = Dispatch.call(wordDocs, "Open", new Variant(path));
            aDoc=va.toDispatch();
            Dispatch docSelection = Dispatch.get(wordApp, "Selection").toDispatch();
            // 3. get active window
            Dispatch activeWindow = wordApp.getProperty("ActiveWindow").toDispatch();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ComThread.Release();
            wordApp.invoke("Quit", new Variant[] {});

        }
    }
}
